/**************************
* @Summary
* @Author 20009200303 赵传博
* @Date 2022/4/26
*****************************/

#include "Tree.h"



Tree::Tree() {
    this->length = 0;
    this->root = nullptr;
}

Tree::Tree(Tnode *root) {
    if(root){
        this->root = root;
        this->length = 1;
    }
}

void Tree::insertNode(Tnode node, Tnode* start) {
    if(!start){
        start = &node;
        return;
    }else if(start->getWord() == node.getWord()){
        start->addCount(node.getCount());
        delete &node;
        return;
    }else if(start->getWord().compare(node.getWord()) > 0){
        if(!start->getLeft()){
            start->setLeft(&node);
            return;
        }else{
            insertNode(node, start->getLeft());
        }
    }else if(start->getWord().compare(node.getWord()) < 0){
        if(!start->getRight()){
            start->setRight(&node);
            return;
        }else{
            insertNode(node, start->getRight());
        }
    }else{
        cerr << "Error" << endl;
    }
}

void Tree::insertNode(string word, Tnode* start) {
    auto* node = new Tnode(word);
    if(!start){
        start = node;
        return;
    }else if(start->getWord() == word){
        start->addCount(node->getCount());
        delete node;
        return;
    }else if(start->getWord().compare(word) > 0){
        if(!start->getLeft()){
            start->setLeft(node);
            return;
        }else{
            delete node;
            insertNode(word, start->getLeft());
        }
    }else if(start->getWord().compare(word) < 0){
        if(!start->getRight()){
            start->setRight(node);
            return;
        }else{
            delete node;
            insertNode(word, start->getRight());
        }
    }else{
        cerr << "Error" << endl;
    }
}

void Tree::printTree(Tnode* start) {
    if(!start) return;
    cout << start->getWord() << "(" << start->getCount() << ")" << " ";
    if(start->getLeft()) printTree(start->getLeft());
    if(start->getRight()) printTree(start->getRight());
}

void Tree::printInOrder(Tnode* start) {
    if(!start) return;
    if(start->getLeft()) printTree(start->getLeft());
    cout << start->getWord() << "(" << start->getCount() << ")" << " ";
    if(start->getRight()) printTree(start->getRight());
}

Tree::~Tree() = default;






